<template>
  <div>
    <!-- 面包鞋导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体区域 -->
    <el-card>
      <el-button type="primary" @click="addRoleDialogVisible = true"
        >添加角色</el-button
      >
      <el-table :data="roleslist" border stripe>
        <!-- 扩展列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 一级权限 -->
            <el-row
              :class="{ bdbottom: true, vcenter: true, bdtop: index == 0 }"
              v-for="(item1, index) in scope.row.children"
              :key="item1.id"
            >
              <el-col :span="5">
                <el-tag
                  closable
                  @close="removeRightById(scope.row, item1.id)"
                  >{{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  :class="{ vcenter: true, bdtop: index != 0 }"
                  v-for="(item2, index) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeRightById(scope.row, item2.id)"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <!-- 三级权限 -->
                    <el-tag
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      type="warning"
                      closable
                      @close="removeRightById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column
          label="角色名称"
          prop="roleName"
          width="150"
        ></el-table-column>
        <el-table-column
          label="角色描述"
          prop="roleDesc"
          width="300"
        ></el-table-column>
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="getRoleInfoById(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoleById(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :show-close="false"
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
      @closed="addRoleDialogClose"
    >
      <el-form :model="newRole" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="newRole.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="newRole.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addRole">确定</el-button>
      </span>
    </el-dialog>
    <!-- 修改角色对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :show-close="false"
      title="修改角色"
      :visible.sync="editRoleDialogVisible"
      width="50%"
      @closed="editRoleDialogClose"
    >
      <el-form :model="editForm" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="editRole">确定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :show-close="false"
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @closed="setRightDialogClose"
    >
      <el-tree
        :data="rightsList"
        :props="treeProps"
        :default-checked-keys="selectedRoleDefaultRights"
        show-checkbox
        node-key="id"
        default-expand-all
        ref="rightsTree"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="allotRights">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 所有角色列表
      roleslist: [],
      //分配权限对话框显示
      setRightDialogVisible: false,
      // 所有权限列表
      rightsList: [],
      // 分配权限树配置
      treeProps: {
        label: "authName",
        children: "children",
      },
      // 选中角色的id
      selectedRoleId: 0,
      // 选中角色的已有权限数组
      selectedRoleDefaultRights: [],
      // 新角色的信息
      newRole: {
        roleName: "",
        roleDesc: "",
      },
      addRoleDialogVisible: false,
      selectedRoleInfo: {},
      editRoleDialogVisible: false,
      editForm: {},
    };
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);

      this.$message.success(res.meta.msg);
      this.roleslist = res.data;
      //   console.log(this.roleslist);
    },
    // 移除角色的指定权限
    removeRightById(role, rightId) {
      this.$confirm("此操作将删除该角色的指定权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          );
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          this.$message.success(res.meta.msg);
          //将返回的新的权限列表重新赋值
          role.children = res.data;
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 展开权限设置对话框
    async showSetRightDialog(role) {
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);

      this.rightsList = res.data;
      this.getLeafkeys(role, this.selectedRoleDefaultRights);
      // 获取当前角色id
      this.selectedRoleId = role.id;
      this.setRightDialogVisible = true;
    },
    // 递归获取所有三级权限
    getLeafkeys(node, arr) {
      if (!node.children) return arr.push(node.id);

      node.children.forEach((element) => {
        this.getLeafkeys(element, arr);
      });
    },
    setRightDialogClose() {
      // 初始化默认选中数组
      this.selectedRoleDefaultRights = [];
    },
    async allotRights() {
      // 通过展开运算符“...”将两个数组拼接
      const rightsId = [
        ...this.$refs.rightsTree.getCheckedKeys(),
        ...this.$refs.rightsTree.getHalfCheckedKeys(),
      ];
      //   得到权限id序列
      const idStr = rightsId.join(",");

      const { data: res } = await this.$http.post(
        `roles/${this.selectedRoleId}/rights`,
        { rids: idStr }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);

      this.$message.success(res.meta.msg);
      this.getRolesList();
      this.setRightDialogVisible = false;
    },
    // 提交新角色
    async addRole() {
      const { data: res } = await this.$http.post("roles", this.newRole);
      if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
      // 刷新列表
      this.getRolesList();
      this.addRoleDialogVisible = false;
      this.$message.success(res.meta.msg);
    },
    addRoleDialogClose() {
      this.newRole = {};
    },
    async getRoleInfoById(roleInfo) {
      this.selectedRoleInfo = roleInfo;

      const { data: res } = await this.$http.get(
        "roles/" + this.selectedRoleInfo.id
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.editForm = res.data;

      this.$message.success(res.meta.msg);
      this.editRoleDialogVisible = true;
    },
    // 修改角色
    async editRole() {
      const { data: res } = await this.$http.put(
        "roles/" + this.editForm.roleId,
        { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      // 刷新数据
      this.selectedRoleInfo.roleName = res.data.roleName;
      this.selectedRoleInfo.roleDesc = res.data.roleDesc;

      this.editRoleDialogVisible = false;
      this.$message.success(res.meta.msg);
    },
    editRoleDialogClose() {
      // 初始化
      this.editForm = {};
    },
    removeRoleById(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("roles/" + id);
          if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
          this.$message.success(res.meta.msg);
          this.getRolesList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },

  created() {
    this.getRolesList();
  },
};
</script>
<style lang='less' scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>